import React, { useRef, useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout'
import { PlusOutlined, UserOutlined } from '@ant-design/icons';
import { Button, Avatar, Switch, message } from 'antd';
import ProTable from '@ant-design/pro-table';
import UserAPI from '@/services/ant-design-pro/user';
import Tools from '@/utils/tools'
import m_config from '@/config/config'
import CreateOrEdit from './components/CreateOrEdit'
const { getUserList, setUserLock, deleteUser } = UserAPI;
const User = (props) => {
    const { dispatch } = props;
    const actionRef = useRef(); // 表格ref，便于自定义操作表格
    const [isModalVisible, setIsModalVisible] = useState(false),
        [editData, setEditData] = useState(undefined),
        [data, setData] = useState({});

    /**
     * 是否禁用用户
     * @param {obj} params 
     */
    const updateUserLock = async (params) => {
        let result = await setUserLock(params);

        if (result.status = 'ok') {
            message.success('操作成功')
        } else {
            message.error('操作成功')
        }
    }

    /**
     * 设置用户数据到state
     * @returns obj(用户列表)
     */
    const setUserData = async () => {
        const result = await getUserList();
        setData(result.data.value);
        return {
            data: result.data.value,
            success: true
        }
    }

    /**
     * 获取用户列表
     * @param {obj} params 搜索参数
     * @returns obj(用户列表)
     */
    const getData = (params) => {
        if (JSON.stringify(data) != "{}") {
            let username = params.username || "",
                email = params.email || "",
                result = data;
            if (username.trim().length > 0 || email.trim().length > 0) {
                result = data.filter((item, index) => {
                    if (username && email) {
                        return item.username.toLowerCase().indexOf(username.toLowerCase()) >= 0
                            && item.email.toLowerCase().indexOf(email.toLowerCase()) >= 0
                    } else if (username) {
                        // return item.username == username
                        return item.username.toLowerCase().indexOf(username.toLowerCase()) >= 0;
                    } else if (email) {
                        // return item.email == email
                        return item.email.toLowerCase().indexOf(email.toLowerCase()) >= 0;
                    }
                })
            }
            return {
                data: result,
                success: true
            }
        }
        return setUserData();
    }

    /**
     * 控制模态框显示与隐藏
     */
    const isShowModal = (show, record = undefined) => {
        setIsModalVisible(show);
        setEditData(record);
    };

    const delUser = async (record) => {
        const result = await deleteUser(record)
        if (result.status == 'ok') {
            await setUserData();
            actionRef.current.reload();
            message.success("删除成功");
        } else {
            message.error('删除失败：' + result.data.message);
            console.log(result.data.error);
        }
    }

    const columns = [
        {
            title: '头像',
            dataIndex: 'avatar_url',
            hideInSearch: true,
            render: (_, record) => (
                <Avatar
                    src={m_config.local + record.avatar_url + record.avatar}
                    size={32}
                    icon={<UserOutlined />}
                />
            )
        },
        {
            title: '姓名',
            dataIndex: 'username',
            copyable: true,
            ellipsis: true,
            formItemProps: {
                rules: [
                    {
                        required: true,
                        message: '此项为必填项',
                    },
                ],
            },
        }, {
            title: '邮箱',
            dataIndex: 'email',
        }, {
            title: '是否禁用',
            dataIndex: 'is_locked',
            hideInSearch: true,
            render: (_, record) => (
                <Switch checkedChildren="启用"
                    unCheckedChildren="禁用"
                    defaultChecked={record.is_locked === -1}
                    onChange={() => {
                        record.is_locked = record.is_locked === -1 ? 1 : -1;
                        updateUserLock(record);
                    }} />
            )
        },
        {
            title: '创建时间',
            dataIndex: 'register_time',
            valueType: 'date',
            hideInSearch: true,
        },
        {
            title: '修改时间',
            dataIndex: 'update_time',
            valueType: 'date',
            hideInSearch: true,
        },
        {
            title: '操作',
            valueType: 'option',
            render: (text, record, _, action) => [
                <a rel="noopener noreferrer" key="edit" onClick={() => isShowModal(true, record)}>
                    编辑
                </a>,
                <a rel="noopener noreferrer" key="del" onClick={() => delUser(record)}>
                    删除
                </a>,
            ],
        }
    ];


    return (
        <PageContainer>

            <ProTable columns={columns} actionRef={actionRef} request={(params = {}, sort, filter) => {
                return getData(params);
            }}
                rowKey="admin_id"
                search={{
                    labelWidth: 'auto'
                }} pagination={{
                    pageSize: 5,
                }} dateFormatter="string" headerTitle="高级表格" toolBarRender={() => [
                    <Button key="button" icon={<PlusOutlined />} type="primary" onClick={() => isShowModal(true)}>
                        新建
                    </Button>,
                ]} />

            {
                isModalVisible ?
                    <CreateOrEdit
                        isModalVisible={isModalVisible}
                        isShowModal={isShowModal}
                        actionRef={actionRef}
                        initData={editData}
                        setUserData={setUserData}
                    /> : ""
            }
        </PageContainer>
    );
}

export default User;